package com.lovi.admin.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lovi.admin.mapper.AdminUserMapper;
import com.lovi.admin.pojo.AdminUser;
import com.lovi.admin.service.AdminUserService;
import com.lovi.admin.utils.CustomAuthenticationToken;
import com.lovi.constant.UserConstant;
import com.lovi.pojo.User;
import com.lovi.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class MyUserRealm extends AuthorizingRealm {
    @Autowired
    AdminUserService userService;
    @Autowired
    AdminUserMapper userMapper;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权-》");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        AdminUser currentUser = (AdminUser) subject.getPrincipal();

        //为0就是有edit的权限
        if(currentUser.getUserRole()==0){
            info.addStringPermission("edit_category");
        }
        return info;
    }


    // 执行认证逻辑
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了 => 认证逻辑AuthenticationToken");

        // 1. 获取自定义的token
        CustomAuthenticationToken customToken = (CustomAuthenticationToken) token;
        AdminUser adminUser = customToken.getAdminUser();
        String password = adminUser.getUserPassword();
        return new SimpleAuthenticationInfo(adminUser, password, "");

    }

    /**
     * 定义支持我们自己写的这个认证token
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof CustomAuthenticationToken;
    }


}
